import { useState } from "react";
import { Button, Form, Input } from "antd-mobile";
import { request } from "../../utils/request";
import { useNavigate } from "react-router-dom";
import { useDispatch } from "react-redux";
import { loginSuccess } from "../../store/user/userSLice";

const Login = () => {
  const [tel, setTel] = useState("");
  const [code, setCode] = useState("");
  const max = 60;
  const [count, setCount] = useState(max);
  const navigate = useNavigate();
  const dispatch = useDispatch()
  const onFinish = async (values) => {
    const resp = await request.post("/user/login", values);
    const { code, data, msg } = resp.data;
    if (code === 200) {
      navigate("/");
      localStorage.setItem("token", data.token);
      localStorage.setItem("userInfo", JSON.stringify(data.userInfo));
      dispatch(loginSuccess(data))
    } else {
      alert(msg);
    }
  };
  const getCode = async () => {
    const telReg = /^1[3-9]\d{9}$/;
    // 0. 检测是不是手机号
    if (telReg.test(tel)) {
      // 2. 倒计时60
      const timer = setInterval(() => {
        setCount((prev) => {
          if (prev <= 1) {
            clearInterval(timer);
            return max;
          }
          return prev - 1;
        });
      }, 1000);

      // 3. 发送一个请求
      const resp = await request.post("/user/captcha", { tel });
      console.log(resp.data.data);
      setCode(resp.data.data);
    } else {
      alert("必须是11位手机号");
    }
  };
  return (
    <div>
      <h2 style={{ textAlign: "center", height: 50, lineHeight: "50px" }}>
        手机号登陆
      </h2>
      <Form
        onFinish={onFinish}
        footer={
          <Button type="submit" block color="primary">
            登陆
          </Button>
        }
      >
        <Form.Item
          name="tel"
          rules={[
            {
              required: true,
              message: "手机号不可以为空",
            },
          ]}
        >
          <Input
            placeholder="请输入手机号"
            value={tel}
            onChange={(value) => setTel(value)}
          ></Input>
        </Form.Item>
        <Form.Item
          name="captcha"
          rules={[
            {
              required: true,
              message: "验证码不可以为空",
            },
          ]}
          extra={
            <Button onClick={() => getCode()}>
              {max === count ? "获取验证码" : `还剩${count}秒重新获取`}
            </Button>
          }
        >
          <Input
            placeholder="验证码"
            value={code}
            onChange={(value) => setCode(value)}
          ></Input>
        </Form.Item>
      </Form>
    </div>
  );
};

export default Login;
